package com.lyb.controller;

import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.lyb.common.AjaxResult;
import com.lyb.common.JWTDemo;
import com.lyb.common.JWTUtils;
import com.lyb.pojo.User;
import com.lyb.services.impl.LoginServiceImpl;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;

@Api(tags="index")
@RestController

public class Index {
    Logger log = LoggerFactory.getLogger(Index.class);
    @Resource
    private JdbcTemplate jdbcTemplate;
    private JWTUtils jwtUtils;
    private JWTDemo jwtDemo;

    @GetMapping("/index")
    public List<User> index(){
        String sql = "select * from user where id=1";
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);
        List<User> user = jdbcTemplate.query(sql,rowMapper);
        return user;
    }
    @GetMapping("/token")
    public String token(){
        Map<String,Object> map = new HashMap<>();
        map.put("id",1);
//        log.info("map"+map);
//        return jwtUtils.getToken(map);
        return jwtDemo.generateJwtToken(map);
    }
    @GetMapping("/verify")
    public Claims verify(String token){
//        return jwtUtils.verify(token);
        return jwtDemo.getClaimsFromJwt(token);
    }
    @GetMapping("/pass")
    @PreAuthorize("hasAuthority('admin')")
    public String pass(){
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return passwordEncoder.encode("123456");
    }
    @Resource
    LoginServiceImpl loginServiceImpl;
    @ApiOperation("登录")
    @PostMapping("/user/login")
    public AjaxResult login(@ApiParam(value="用户",required=true) @RequestBody User user){

        return loginServiceImpl.Login(user);
    }
}
